package com.example.demo;

import org.junit.Test;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;

/**
 * https://leetcode.cn/problems/reverse-substrings-between-each-pair-of-parentheses/
 */
public class ReverseParentheses {

    @Test
    public void test() {
        String s = reverseParentheses("(u(love)i)");
        System.out.println(s);
    }

    public String reverseParentheses(String s) {
        Stack<String> stack = new Stack<>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (ch == '(') {
                stack.push(sb.toString());
                sb.setLength(0);
            } else if (ch == ')') {
                sb.reverse();
                sb.insert(0, stack.pop());
            } else {
                sb.append(ch);
            }
        }
        return sb.toString();
    }

    public String reverseParentheses2(String s) {
        Stack<String> stack = new Stack<>();

        for (char c : s.toCharArray()) {
            if (c != ')') {
                stack.push(String.valueOf(c));
            } else {
                StringBuilder sb = new StringBuilder();
                while (true) {
                    String pop = stack.pop();
                    if (!pop.equals("(")) {
                        sb.append(pop);
                    } else {
                        for (int j = 0; j < sb.length(); j++) {
                            stack.push(sb.substring(j, j + 1));
                        }
                        break;
                    }
                }
            }
        }

        StringBuilder sb = new StringBuilder();
        stack.forEach(sb::append);
        return sb.reverse().toString();
    }
}
